<template>
  <div class="playing-room">
    <div class="playing-header">
      <div class="playing-back" @click="backListRoom()">
        <img src="../assets/picture/game_back.png" width="54" height="54">
      </div>
      <div class="wrap-recharge">
        <div class="recharge-bg"></div>
        <div class="recharge-mb" v-if="!scratch" @click="jumpCharge()">
          <div class="center-surplus"><p>{{roomInfo.coin}}喵币</p></div>
          <img class="miaobi-icon" src="../assets/picture/miaobi-icon.png" width="28" height="28">
          <img class="recharge-icon" src="../assets/picture/recharge-miaobi.png" width="30" height="30">
        </div>
        <div class="surplus-time" v-else>
          <p>倒计时&nbsp;{{surplusTime}}S</p>
        </div>
      </div>
      <div class="playing-people">
        <img class="player-pic" :src="isPlaying ? hasPeople : nobody" width="50" height="50">
        <img class="tips" :src="isPlaying ? onePlayer : hasNothing" width="40" height="20">
      </div>
    </div>
    <div id="video-streaming">
      <!--<div id="agora_local" style="float:right;width:210px;height:147px;display:inline-block;"></div>-->
    </div>
    <canvas id="jsmpeg-player" :style="{width: 'auto', height: videoHeight + 'px', marginLeft: -140 + 'px'}"></canvas>
    <canvas id="jsmpeg-player2" :style="{width: 'auto', height: videoHeight + 'px', marginLeft: -140 + 'px'}"></canvas>
    <div class="wrap-bottom-info">
      <div class="bottom-play" v-if="!scratch">
        <div class="wrap-game" @click="playGame()">
          <img :src="touchOperate ? startGame : touchStartGame" width="145" height="77" @touchmove="changeStatus()" @touchend="initStatus()">
          <div class="play-info">
            <div class="wrap-info">
              <img class="mb-icon" src="../assets/picture/miaobi-icon.png" width="19" height="19">
              <p>{{roomInfo.roomCoin}}喵币/次</p>
            </div>
          </div>
          <div class="play-game">
            <p>开始游戏</p>
          </div>
        </div>
      </div>
      <div class="operate-game" v-else>
        <div v-if="frontage">
          <button class="up" style="width: 62px; height: 62px; background: url('https://ohwflolko.qnssl.com/up-operate.png') no-repeat; background-size: 62px 62px;outline: none;border: none;" @touchstart="controlOperate('UP')" @touchend="controlOperate('UPSTOP')"></button>
          <button class="right" style="width: 62px; height: 62px; background: url('https://ohwflolko.qnssl.com/right-operate.png') no-repeat; background-size: 62px 62px;outline: none;border: none;" @touchstart="controlOperate('RIGHT')" @touchend="controlOperate('RIGHTSTOP')"></button>
          <button class="bottom" style="width: 62px; height: 62px; background: url('https://ohwflolko.qnssl.com/dowm-operate.png') no-repeat; background-size: 62px 62px;outline: none;border: none;" @touchstart="controlOperate('DOWN')" @touchend="controlOperate('DOWNSTOP')"></button>
          <button class="left" style="width: 62px; height: 62px; background: url('https://ohwflolko.qnssl.com/left-operate.png') no-repeat; background-size: 62px 62px;outline: none;border: none;" @touchstart="controlOperate('LEFT')" @touchend="controlOperate('LEFTSTOP')"></button>
        </div>
        <div v-else>
          <button class="up" style="width: 62px; height: 62px; background: url('https://ohwflolko.qnssl.com/up-operate.png') no-repeat; background-size: 62px 62px;outline: none;border: none;" @touchstart="controlOperate('LEFT')" @touchend="controlOperate('LEFTSTOP')"></button>
          <button class="right" style="width: 62px; height: 62px; background: url('https://ohwflolko.qnssl.com/right-operate.png') no-repeat; background-size: 62px 62px;outline: none;border: none;" @touchstart="controlOperate('UP')" @touchend="controlOperate('UPSTOP')"></button>
          <button class="bottom" style="width: 62px; height: 62px; background: url('https://ohwflolko.qnssl.com/dowm-operate.png') no-repeat; background-size: 62px 62px;outline: none;border: none;" @touchstart="controlOperate('RIGHT')" @touchend="controlOperate('RIGHTSTOP')"></button>
          <button class="left" style="width: 62px; height: 62px; background: url('https://ohwflolko.qnssl.com/left-operate.png') no-repeat; background-size: 62px 62px;outline: none;border: none;" @touchstart="controlOperate('DOWN')" @touchend="controlOperate('DOWNSTOP')"></button>
        </div>
        <img class="scratch" src="../assets/picture/catch.png" width="90" height="90" @touchstart="controlOperate('CATCH')">
      </div>
    </div>
    <div class="direction" @click="changeDirection($event)">
      <button style="width: 52px; height: 52px; background: url('https://ohwflolko.qnssl.com/qiehuan.png') no-repeat; background-size: 52px 52px;outline: none;border: none;"></button>
    </div>
    <model ref="modelInfo" v-show="MiaozhuaTips">
      <div v-if="scratchEnd" class="two-btn">
        <p>
          <span @click="hideModel()">下次吧</span>
          <span @click="hideModel()">再玩一次</span>
        </p>
      </div>
      <p v-else @click="hideModel()" class="one-btn">确定</p>
    </model>
  </div>
</template>

<script>
  import onOne from '../assets/picture/noone.png'
  import model from '../components/model.vue'
  export default {
    name: 'playing',
    components: {
      model
    },
    data () {
      return {
        isPlaying: false, // 是否有玩家正在抓娃娃
        touchOperate: false,  // 是否在触摸开始游戏按钮
        nobody: onOne,  //  没有玩家在玩游戏时的默认图
        hasPeople: '',  // 有玩家在玩游戏时的玩家头像
        miaobiNumber: 0,  // 用户拥有喵币
        hasNothing: require('../assets/picture/hasnothing.png'),
        onePlayer: require('../assets/picture/onePlayer.png'),
        startGame: require('../assets/picture/start.png'),
        touchStartGame: require('../assets/picture/start_sel.png'),
        modelFail: require('../assets/picture/modelFail.png'),
        modelSuccess: require('../assets/picture/modelSuccess.png'),
        modelTips: require('../assets/picture/modelTips.png'),
        roomInfo: '', // 房间信息
        scratch: false,  // 是否本人正在抓娃娃
        hasHeader: '',
        roomId: '', // 房间号
        userId: '', // 玩家id
        channel: '', // 频道号
        frontage: true,  // 是否是正面
        channelOther: '', // 侧面视频频道号
        gameTime: '',  // 游戏时间
        surplusTime: '', // 剩余游戏时间
        websocket: '',
        MiaozhuaTips: false, // 是否显示model
        scratchEnd: false, // 是否是游戏结束
        videoHeight: '',
        timer: null
      }
    },
    created () {
      document.documentElement.style.cssText += 'height: 100%;'
      document.body.style.cssText += '; position: fixed; height: 100%; overflow: hidden; width: 100%; background: #000000!important;'
    },
    beforeMount () {
      this.videoHeight = (document.body.clientHeight > document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight) - 150
      this.hasHeader = this.$utils.getQueryStringByName('token') ? this.$utils.getQueryStringByName('token') : this.$utils.getCookie('WAWA_TOKEN')
    },
    mounted () {
      // android 微信内禁止复制
      var node = document.querySelector('.playing-room')
      node.addEventListener('contextmenu', function (e) {
        e = window.event || event
        e.preventDefault()
      })
      this.roomId = this.$route.query.roomId
      this.roomDetail()
      // this.$refs.modelInfo.showModel(this.modelTips, '请检查余额是否充足', '还不能开始哦，请稍后再试')
      this.websocket = new WebSocket('ws://www.likewawa.com:8080/miaozhuapc/wawa/control')
      var that = this
      that.websocket.onopen = function () {
        that.websocket.send('{"extra":"","data":"","type":"ROOM", "room":' + that.roomId + '}')
      }
    },
    updated () {
      this.acceptMessage()
    },
    methods: {
      jumpCharge () {
        this.$router.push({path: '/recharge'})
      },
      changeStatus () {
        this.touchOperate = true
      },
      initStatus () {
        this.touchOperate = false
      },
      backListRoom () {
        this.$router.go(-1)
      },
      hideModel () {
        this.MiaozhuaTips = false
      },
      roomDetail () {
        this.$http({
          method: 'get',
          url: 'https://www.likewawa.com/miaozhuapc/v1/room/roomDetail',
          headers: {'WAWA_TOKEN': this.hasHeader},
          params: {'roomId': this.roomId},
          emulateJSON: true
        }).then(function (response) {
          console.log(response)
          response = JSON.parse(response.bodyText)
          console.log(response)
          this.roomInfo = response.body
          this.userId = response.body.userId
          this.channel = response.body.videoNormal
          this.channelOther = response.body.videoRight
          this.gameTime = response.body.gameTime
          this.$nextTick(() => {
            this.videoStreaming()
          })
        }, function () {
          console.log('稍后重试')
        })
      },
      // 消息接收
      acceptMessage () {
        var that = this
        // 返回消息
        that.websocket.onmessage = function (event) {
          var msg = event.data
          console.dir(msg)

          event = window.event || event
          if (!that.$utils.isJsonString(event.data)) {
            return false
          } else {
            msg = JSON.parse(event.data)
          }
          if (msg.type === 'CANPLAY') {
            that.isPlaying = false
          } else if (msg.type === 'AVAILABLE') {
            that.scratch = true
            that.surplusTime = that.gameTime
            that.surplusDown(that.surplusTime)
            that.miaobiNumber = msg.data
          } else if (msg.type === 'PLAYER') {
            that.isPlaying = true
            that.hasPeople = msg.data
          } else if (msg.type === 'NOTAVAILABLE') {
            // alert('还不能开始游戏')
            that.MiaozhuaTips = true
            that.scratchEnd = false
            that.$refs.modelInfo.showModel(that.modelTips, '请检查余额是否充足', '还不能开始哦，请稍后再试')
          } else if (msg.type === 'CANNOTSTART') {
            // alert('还有玩家在游戏中')
            return false
          } else if (msg.type === 'END') {
            clearInterval(that.timer)
            that.isPlaying = false
            that.MiaozhuaTips = true
            that.scratch = false
            that.scratchEnd = true
            if (msg.data === 'SUCCESS') {
              // alert('恭喜你！抓中了')
              that.$refs.modelInfo.showModel(that.modelSuccess, '哎呀，你抓到我啦', '还有更多的小伙伴等待你抓捕哟')
            } else {
              // alert('哈哈哈哈！你抓不到我（逃）')
              that.$refs.modelInfo.showModel(that.modelFail, '差一点就抓到了', '再玩一次你一定可以抓到的')
            }
          }
        }
        that.websocket.onerror = function () {
          that.$refs.modelInfo.showModel(that.modelFail, '连接中断了', '')
        }
      },
      // 判断是否能开始游戏
      playGame () {
        var that = this
        that.websocket.send('{"extra":"","data":' + that.userId + ',"type":"START", "room": ' + that.roomId + '}')
      },
      // 控制操作
      controlOperate (instruct) {
        var that = this
        console.log(that)
        that.websocket.send('{"extra":"","data":' + instruct + ',"type":"CMD", "room": ' + that.roomId + '}')
      },
      // 倒计时
      surplusDown: function (count) {
        var that = this
        that.timer = setInterval(function () {
          count -= 1
          that.surplusTime = count
          if (count === 0) {
            clearInterval(that.timer)
            that.controlOperate('CATCH')
            that.scratch = false
          }
        }, 1000)
      },
      changeDirection (e) {
        e = window.event || event
        e.preventDefault()
        this.frontage = !this.frontage
        this.$nextTick(() => {
          this.videoStreaming()
        })
      },
      // 直播
      videoStreaming () {
        this.$http({
          method: 'post',
          url: 'https://h5cs-1.agoraio.cn:7668/geth5gw/jsonp',
          headers: {'Content-type': 'application/json; charset=utf-8'},
          body: JSON.stringify({key: 'a97c67d05ab64a17a576cc759062966f', cname: '1500'}),
          emulateJSON: true
        }).then(function (response) {
          response = JSON.parse(response.bodyText)
          if (response && response.gateway_addr) {
            var domain = response.gateway_addr[0]
            this.streamPlay(domain)
          }
        }, function () {
          console.log('稍后重试')
        })
      },
      streamPlay (domain) {
        this.$http({
          method: 'post',
          url: 'https://' + domain + '/v1/machine',
          body: {appid: 'a97c67d05ab64a17a576cc759062966f', channel: this.channel, uid1: 1, uid2: 2},
          emulateJSON: true
        }).then(function (json) {
          json = JSON.parse(json.bodyText)
          var url = ''
          var videoPlay = ''
          var videoPlay1 = document.getElementById('jsmpeg-player')
          var videoPlay2 = document.getElementById('jsmpeg-player2')
          if (this.frontage) {
            url = json.cameras.main
            videoPlay = videoPlay1
            videoPlay1.style.display = 'block'
            videoPlay2.style.display = 'none'
          } else {
            url = json.cameras.sub
            videoPlay = videoPlay2
            videoPlay2.style.display = 'block'
            videoPlay1.style.display = 'none'
          }
          var player1 = new window.JSMpeg.Player(url, {
            canvas: videoPlay,
            audio: !1,
            onDidDecodeFirstFrame: function () {

            },
            onConnectionEstablished: function () {

            },
            onFirstPacketReceived: function () {

            },
            onWillDecodeFirstFrame: function () {

            }
          })
        }, function () {
          console.log('稍后重试')
        })
      }
    },
    destroyed () {
      document.documentElement.style.cssText += 'height: auto;'
      document.body.style.cssText += '; position: static; height: auto; overflow: auto; background: none;'
      var that = this
      that.websocket.onclose = function () {
        that.websocket.close() // 关闭TCP连接
      }
    }
  }
</script>

<style scope lang="scss">
  .playing-room{
    -webkit-user-select:none;
    -webkit-touch-callout:none;
  }
  .playing-header{
    overflow: hidden;
    position: relative;
    padding-bottom: 5px;
    .playing-back{
      float: left;
      margin: 13px 0 0 12px;
      position: relative;
      z-index: 999;
      img{
        display: inherit;
      }
    }
    .recharge-bg{
      width: 189px;
      height: 42px;
      position: absolute;
      top: 17px;
      left: 50%;
      margin-left: -95px;
      opacity: 0.3;
      border-radius: 21px;
      background-color: #ffffff;
      z-index: 9;
    }
    .recharge-mb{
      width: 189px;
      height: 42px;
      position: absolute;
      top: 17px;
      left: 50%;
      margin-left: -95px;
      border-radius: 21px;
      z-index: 10;
      .center-surplus{
        display: block;
        position: absolute;
        z-index: 99;
        width: 100%;
        p{
          font-size: 18px;
          color: #ffffff;
          font-weight: bold;
          line-height: 42px;
          text-align: center;
        }
      }
      .miaobi-icon{
        position: absolute;
        z-index: 99;
        left: 7px;
        top: 50%;
        margin-top: -14px;
      }
      .recharge-icon{
        position: absolute;
        z-index: 99;
        right: 7px;
        top: 50%;
        margin-top: -15px;
      }
    }
    .surplus-time{
      width: 189px;
      height: 42px;
      position: absolute;
      top: 17px;
      left: 50%;
      margin-left: -95px;
      border-radius: 21px;
      z-index: 10;
      p{
        font-size: 18px;
        color: #ffffff;
        text-align: center;
        line-height: 42px;
        font-style:oblique;
      }
    }
    .playing-people{
      float: right;
      position: relative;
      z-index: 99;
      margin-top: 13px;
      margin-right: 12px;
      .player-pic{
        border-radius: 50%;
        border: 2px solid #ffdf58;
      }
      .tips{
        position: absolute;
        bottom: -5px;
        left: 50%;
        margin-left: -20px;
        z-index: 199;
      }
    }
  }
  div#video-streaming {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    video{
      width: 135% !important;
      height: 82% !important;
      position: absolute !important;
      top: 0 !important;
      left: -67px !important;
    }
  }
  canvas#jsmpeg-player, canvas#jsmpeg-player2 {
    position: absolute;
    top: calc(50% - 75px);
    transform: translateY(-50%);
  }
  .wrap-bottom-info{
    height: 150px;
    width: 100%;
    background: #ffdf58;
    position: absolute;
    bottom: 0px;
    .operate-game{
      /* 禁止选取 */
      button{
        -webkit-user-select:none;
        -moz-user-select:none;
        -ms-user-select:none;
        user-select:none;
        -webkit-touch-callout: none;
      }
      /*img{
        pointer-events: none; // 禁止点击
      }*/
      .up{
        position: absolute;
        top: 5px;
        left: 99px;
      }
      .right{
        position: absolute;
        top: 44px;
        left: 175px;
      }
      .bottom{
        position: absolute;
        bottom: 2px;
        left: 99px;
      }
      .left{
        position: absolute;
        top: 44px;
        left: 22px;
      }
      .scratch{
        position: absolute;
        top: 30px;
        right: 20px;
      }
    }
  }
  .bottom-play{
    /* width: 100%;
    background: #ffdf58;
    position: absolute;
    bottom: 0px; */
    margin-top: 35px;
    .wrap-game{
      position: relative;
      bottom: 40px;
      left: 50%;
      margin-left: -72.5px;
      display: table;
      top: 0px;
      -webkit-user-select:none;
      -moz-user-select:none;
      -ms-user-select:none;
      user-select:none;
      .play-info{
        position: absolute;
        top: 13px;
        width: 100%;
        .wrap-info{
          display: table;
          margin: 0 auto;
          overflow: hidden;
          img{
            margin-right: 7px;
            float: left;
            pointer-events: none;
          }
          p{
            font-size: 14px;
            font-weight: bold;
            color: #1e1e1b;
            float: left;
            /* text-shadow: 0 2px #1e1e1b, 2px 0 #1e1e1b, -2px 0 #1e1e1b, 0 -2px #1e1e1b; */
          }
        }
      }
      .play-game{
        position: absolute;
        bottom: 20px;
        width: 100%;
        p{
          font-size: 17px;
          color: #ff5371;
          font-weight: bold;
          /* text-shadow: 0 2px #1e1e1b, 2px 0 #1e1e1b, -2px 0 #1e1e1b, 0 -2px #1e1e1b; */
          text-align: center;
        }
      }
    }
  }
  .direction{
    position: fixed;
    top: 50%;
    transform: translateY(-50%);
    right: 0;
    /*pointer-events: none;*/
    button{
      -webkit-user-select:none;
      -moz-user-select:none;
      -ms-user-select:none;
      user-select:none;
    }
  }
  @media screen and (max-width: 360px){
    .wrap-bottom-info{
      .operate-game{
        .up{
          left: 80px;
        }
        .right{
          position: absolute;
          top: 44px;
          left: 154px;
        }
        .bottom{
          position: absolute;
          bottom: 2px;
          left: 80px;
        }
        .left{
          position: absolute;
          top: 44px;
          left: 3px;
        }
        .scratch{
          position: absolute;
          top: 30px;
          right: 10px;
        }
      }
    }
  }
</style>
